package com.tdk.mybatisplus.demo.common.util;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.tdk.mybatisplus.demo.common.entity.Constants;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 时间戳转换
 * </p>
 *
 * @author: taodingkai
 * @modified:
 * @since: 2022/5/24 11:59 
 */
@Slf4j
public class TimestampStringConverter implements Converter<Timestamp> {
 
    @Override
    public Class<Timestamp> supportJavaTypeKey() {
        return Timestamp.class;
    }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
    
    @Override
    public Timestamp convertToJavaData(
        ReadCellData<?> cellData,
                                  ExcelContentProperty excelContentProperty,
                                  GlobalConfiguration globalConfiguration) throws Exception {
        return strToSqlDate(cellData.getStringValue(), Constants.DATE_PATTERN);
    }
    
    @Override
    public WriteCellData<String> convertToExcelData(Timestamp value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return new WriteCellData<String>(DateUtil.format(value, Constants.DATE_PATTERN));
    }
    
    /**
     * 字符串转时间戳
     *
     * @param strDate 字符串日期
     * @param dateFormat 日期格式
     * @return
     */
    public static Timestamp strToSqlDate(String strDate, String dateFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        java.util.Date date = null;
        try {
            date = sf.parse(strDate);
        } catch (Exception e) {
            log.error("时间转换失败", e);
        }
        if (Objects.nonNull(date)) {
            return new Timestamp(date.getTime());
        }
        return null;
    }
}
